//index.js
//获取应用实例
const app = getApp()
Page({
  data: {
    list: [
      '有效领取日期：2020.5.14-10:00~2020.5.31-19:59',
      '吉买盛彭浦店',
      '门店地址：上海市静安区临汾路500号',
      '换行地址，在请求到地址时处理',
      '联系电话：135xxxxxxxxx'
    ]
  },
  onLoad: function (options) {
    this.setCanvasSize() //设设置适配比例
    this.getimgResources() //获取图片资源
  },
  onShow() {
    let $this = this
    setTimeout(() => {
      $this.draw()
    }, 1000); //延迟用于数据处理等待时间
  },
  // 设置适配比例
  setCanvasSize: function () {
    let $this = this
    var res = wx.getSystemInfoSync();
    var scale = 750 / res.windowWidth; //不同屏幕下canvas的适配比例；设计稿是750宽   
    // w = 515/scale     canvas尺寸=设计尺寸/scale
    $this.setData({
      scale
    })
  },

  //绘制canvas内容
  draw() {
    let $this = this
    let bgimg = this.data.bgimg
    let scale = this.data.scale
    let ctx = wx.createCanvasContext('mycanvas', this);
    // ctx.globalAlpha = 0;
    ctx.setFillStyle('#FFFFFF')
    ctx.fillRect(0, 0, 515 / scale, 300 / scale);
    ctx.clearRect(0, 0, 515 / scale, 300 / scale);
    let list = this.data.list
    ctx.globalAlpha = 1;
    ctx.drawImage(bgimg, 0, 0, 515 / scale, 300 / scale); //绘制背景图片
    ctx.setFillStyle("#FFF")
    ctx.setFontSize(18 / scale)
    // for (const index in list) {
    let index = 0
    let canvastime = setInterval(() => {
      let y = 134 + index * 30
      console.log(index)

      ctx.save()
      ctx.restore()
      ctx.fillText(list[index], 40 / scale, y / scale)
      // ctx.stroke()
      ctx.draw(true);
      ctx.restore()
      index++
      if (index == list.length) {
        clearInterval(canvastime)
      }
    }, 1000)

    // }

    console.log(222)
    // setTimeout(() => {
    //   $this.extraImage
    // }, 2000);
  },
  // 绘制成本地图片
  extraImage() {
    console.log(222)
    let $this = this
    wx.canvasToTempFilePath({
      canvasId: 'mycanvas',
      quality: 1,
      success: (res) => {
        let filePath = res.tempFilePath; //获取图片地址
        $this.setData({
          imageUrl: res.tempFilePath, //图片地址保存到本地
        })
      }
    }, this)
    console.log(this)
    // 提取画布中容器所在区域内容生成相同大小的图片，返回临时文件地址
  },
  // 获取图片资源 
  getimgResources() {
    let $this = this
    wx.downloadFile({
      url: 'https://totolestorage.blob.core.chinacloudapi.cn/totoleec/mgm/image-card.png', //图片 
      success: (res) => {
        $this.setData({
          bgimg: res.tempFilePath
        })
        console.log($this.data.bgimg)
      }
    })
  },
})